// GridArea.tsx（网格容器，接收拖拽的物料）
import React, { useState, useRef } from 'react';
import { useDrop } from 'react-dnd';
import type { GridWidget, WidgetMaterial, GridConfig } from './types';
import DraggableResizableWidget from './DraggableResizableWidget.tsx'; // 下文实现

const GridArea: React.FC = () => {
  // 网格配置
  const gridConfig: GridConfig = { cellSize: 20, rows: 20, cols: 20 };
  // 网格内组件实例列表
  const [widgets, setWidgets] = useState<GridWidget[]>([]);
  // 网格容器 DOM 引用（用于计算拖拽位置）
  const gridRef = useRef<HTMLDivElement>(null);

  // 定义放置目标
  const [, drop] = useDrop(() => ({
    accept: 'WIDGET', // 接收的拖拽类型
    drop: (item: WidgetMaterial, monitor) => {
      // 计算物料放置在网格内的相对位置
      if (!gridRef.current) return;
      const gridRect = gridRef.current.getBoundingClientRect();
      const clientOffset = monitor.getClientOffset();
      if (!clientOffset) return;

      // 计算相对坐标（基于网格容器）
      const x = clientOffset.x - gridRect.left;
      const y = clientOffset.y - gridRect.top;

      // 对齐到网格（可选）
      const snappedX = Math.round(x / gridConfig.cellSize) * gridConfig.cellSize;
      const snappedY = Math.round(y / gridConfig.cellSize) * gridConfig.cellSize;

      // 创建网格内组件实例
      const newWidget: GridWidget = {
        ...item,
        gridId: `widget-${Date.now()}`, // 生成唯一 ID
        x: snappedX,
        y: snappedY,
        width: item.initialWidth,
        height: item.initialHeight,
        rotation: 0,
        zIndex: 1,
      };

      // 添加到网格
      setWidgets((prev) => [...prev, newWidget]);
    },
  }));

  // 更新组件状态（位置/大小/旋转）
  const updateWidget = (updatedWidget: GridWidget) => {
    setWidgets((prev) => prev.map((w) => (w.gridId === updatedWidget.gridId ? updatedWidget : w)));
  };

  return (
    <div
      ref={(node) => {
        gridRef.current = node;
        drop(node); // 绑定放置目标到网格容器
      }}
      style={{
        width: '100%',
        height: '600px',
        border: '1px solid #eee',
        position: 'relative',
        backgroundImage: `linear-gradient(to right, #f0f0f0 ${gridConfig.cellSize - 1}px, transparent 1px),
                         linear-gradient(to bottom, #f0f0f0 ${gridConfig.cellSize - 1}px, transparent 1px)`,
        backgroundSize: `${gridConfig.cellSize}px ${gridConfig.cellSize}px`,
      }}
    >
      {/* 渲染网格内所有组件 */}
      {widgets.map((widget) => (
        <DraggableResizableWidget key={widget.gridId} widget={widget} gridConfig={gridConfig} onUpdate={updateWidget} />
      ))}
    </div>
  );
};

export default GridArea;
